#!/usr/bin/env python3

#  VT码命令前缀
PR = '\033['

#  光标操作定义
SAVE, LOAD, HIDE, SHOW = 's', 'u', '?25l', '?25h'

#  清除操作定义
SCREEN, LINE, END = '2J', '2K', 'K'

#  颜色定义
BLACK, RED, GREEN, YELLOW, BLUE, PURPLE, CYAN, WHITE, DEFAULT = range(9)

#  方向定义
UP, DOWN, LEFT, RIGHT = "ABDC"


#  绝对定位
def goto(r, c, back):
    if back:
        return "%s%d;%dH" % (PR, r, c)
    else:
        print("%s%d;%dH" % (PR, r, c), end='', flush=True)

#  相对定位
def move(direction, step, back):
    if back:
        return "%s%d%s" % (PR, step, direction)
    else:
        print("%s%d%s" % (PR, step, direction), end='', flush=True)

def left(step, back):
    return move(LEFT, step, back)

def right(step, back):
    return move(RIGHT, step, back)

def up(step, back):
    return move(UP, step, back)

def down(step, back):
    return move(DOWN, step, back)

#  光标操作
def run(cmd, back):
    if back:
        return "%s%s" % (PR, cmd)
    else:
        print("%s%s" % (PR, cmd), end='', flush=True)

def save(back):
    return run(SAVE, back)

def load(back):
    return run(LOAD, back)

def hide(back):
    return run(HIDE, back)

def show(back):
    return run(SHOW, back)

#  清除操作
def clear(back):
    return run(SCREEN, back)

def clearLine(back):
    return run(LINE, back)

def clearLineEnd(back):
    return run(END, back)

#  颜色输出
def setColor(fg, bg, bold):
    if bold:
        print("%s%d;%d;1m" % (PR, fg + 30, bg + 40), end='', flush=True)
    else:
        print("%s%d;%dm" % (PR, fg + 30, bg + 40), end='', flush=True)

def color(s, fg, bg, bold):
    if bold:
        print("%s%d;%d;1m%s\033[0m" % (PR, fg + 30, bg + 40, s),
                end='', flush=True)
    else:
        print("%s%d;%dm%s\033[0m" % (PR, fg + 30, bg + 40, s),
                end='', flush=True)

def clearStyle():
    print("%s0m" % (PR), end='', flush=True)


#  vt测试
if __name__ == "__main__":
    #  clear(False)
    #  goto(1, 1, False)
    #  run(HIDE, False)
    #  setColor(RED, DEFAULT, False)
    #  print("1hello world")
    #  clearStyle()
    #  print("2hello world")
    #  color("3hello world", YELLOW, BLACK, True)
    #  input()
    #  run(SHOW, False)

    print(clear(True) + goto(1, 1, True) + run(HIDE, True), end='', flush=True)
    setColor(RED, DEFAULT, False)
    print("1hello world")
    clearStyle()
    print("2hello world")
    color("3hello world", YELLOW, BLACK, True)
    input()
    run(SHOW, False)




